package com.small.wechat.email.controller;

import com.google.common.collect.RangeSet;
import com.small.wechat.email.MailService;
import com.small.wechat.email.entity.HtmlMailVo;
import com.small.wechat.email.entity.SimpleMailVo;
import com.small.wechat.result.Result;
import com.small.wechat.result.ResultSet;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.EngineContext;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Map;


/**
 * 邮箱
 *
 * @author wangguochao
 */
@RestController
@AllArgsConstructor
@RequestMapping("/email")
public class EmailController {
    private final MailService mailService;
    private final TemplateEngine templateEngine;

    /**
     * 简单邮件
     *
     * @param param 参数
     * @return 结果
     */
    @PostMapping()
    public Result<?> simpleMail(@RequestBody @Validated SimpleMailVo param) {
        mailService.sendSimpleMail(param.getRecipient(), param.getTitle(), param.getContent());
        return ResultSet.success();
    }

    /**
     * 模版邮件
     *
     * @param param 参数
     */
    @PostMapping("html")
    public Result<?> sendHtmlMail(@RequestBody @Validated HtmlMailVo param) {
        Context ctx = new Context();
        Map<String, Object> map = param.getMap();
        for (String key : map.keySet()) {
            ctx.setVariable(key, map.get(key));
        }
        String result = templateEngine.process(param.getStencil(), ctx);
        mailService.sendHtmlMail(param.getRecipient(), param.getTitle(), result);
        return ResultSet.success();
    }
}
